package by.bsu.touragency.db.connection;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;

public class DBConnector {

	private static Logger logger = Logger.getLogger("log");
	public static final String JDBC_CONTEXT_PATH = "java:/comp/env/jdbc/AdmissionSystem";
	private Connection connection;
	private Statement statement;
	private PreparedStatement preparedStatement;

	public DBConnector() {
		// v4 use context.xml & ewb.xml
		Context initCtx;
		try {
			initCtx = new InitialContext();

			Context envCtx = (Context) initCtx.lookup("java:comp/env");
			DataSource ds = (DataSource) envCtx.lookup("jdbc/tourAgency");

			connection = ds.getConnection();

		} catch (NamingException e) {
			logger.error(e);
		} catch (SQLException e) {
			logger.error(e);
		}

		// v4 end
	}

	public Connection getConnection(){
		if (connection != null) {
			return connection;
		}else {
			logger.error("Connection is null");
			return connection;
		}
	}

	public PreparedStatement getPreparedStatement(String sql){
		if (connection != null) {
			try {
				preparedStatement = connection.prepareStatement(sql);
			} catch (SQLException e) {
				logger.error("PrepareStatement is null");
			}
			if (preparedStatement != null) {
				return preparedStatement;
			}
		}
		return preparedStatement;
	}

	public Statement getStatement()  {
		if (connection != null) {
			try {
				statement = connection.createStatement();
			} catch (SQLException e) {
				logger.error("Statement is null");
			}
			if (statement != null) {
				return statement;
			}
		}
		return statement;
	}

	public void close() {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException ex) {
				logger.error(ex);
			}
		}
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException ex) {
				logger.error(ex);
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException ex) {
				logger.error(ex);
			}
		}
	}
}
